var firstLoad = true;
var filteredData;
fixPositionsOfFrozenDivs = function () {
	if (typeof this.grid.fbDiv !== "undefined") {
		$(this.grid.fbDiv).css($(this.grid.bDiv).position());
	}
	if (typeof this.grid.fhDiv !== "undefined") {
		$(this.grid.fhDiv).css($(this.grid.hDiv).position());
	}
};

function getCurrentCondition() {
	// turn on first load flag
	firstLoad = true;
	
	// set search parameters.
	var customername = $("#customername").val();
	var prios = [];
	$("input[name='priority']:checked").each(
		function(){
			prios.push($(this).val());
		}
	);
	var prodarea = [];
	$("input[name='prodarea']:checked").each(
		function(){
			prodarea.push($(this).val());
		}
	);
	var prodarea = [];
	$("input[name='prodarea']:checked").each(
		function(){
			prodarea.push($(this).val());
		}
	);
	var department = [];
	$("input[name='department']:checked").each(
		function(){
			department.push($(this).val());
		}
	);
	var holdcode = $("select[name=selectedHCFilter]").val();
	holdcode = $("select[name=selectedHCFilter] option:selected").text() + '+=+' + holdcode;
	
	var holdreason = $('#holdreason').val();
	
	return {priority: prios, prodarea: prodarea, 
		department: department, customername: customername,
		holdcode: holdcode, holdreason: holdreason};
}

function populateData(lotStatusModel) {
	var mygrid = jQuery("#s3list")
		.jqGrid(
				{
					url : 'search.do',
					datatype : "json",
					postData: getCurrentCondition(),
					
					height: 456,
					colNames : lotStatusModel.colNames,
					colModel : lotStatusModel.colModel,
					rowNum : 200,
					width : 300,
					mtype : "POST",
					rowList : [ 200, 300, 500 ],
					pager : '#s3pager',
					sortname : lotStatusModel.defaultSortColumn,
					viewrecords : true,
					rownumbers : true,
					sortorder :  "asc", //"desc"
					headertitles : true,
					gridview : true,
					scrolling: true,
					autowidth: false,
					shrinkToFit: false,
					loadonce: true,
					multiselect: true,
					//beforeSelectRow: handleMultiSelect, // handle multi select
					ignoreCase: true,
					caption:"MEMS LOT STATUS (" + lotStatusModel.currentDate + ")",
					onHeaderClick: function (stat) {
				    	if(stat == 'visible' ){
				    		jQuery("#filter").css("display","none");
				    	}
					},
					beforeSelectRow: function(rowid, e){
						if(e.target.type == "checkbox"){
							return true;
						}
						return false;
				    },
					loadComplete: function (data) {
						filteredData = data.rows;
					},
					gridComplete: function() {
						var ids = jQuery('#s3list').getDataIDs();
						
						if (firstLoad && ids.length > 0) {
							//	update current time
							jQuery("#s3list").setCaption("MEMS LOT STATUS " + displayNiceDateFormat(new Date()));
							// reset firstLoad
							firstLoad = false;
						}
						
						
						for (var i = 0, idCount = ids.length; i < idCount; i++) {
				    		color ='';
				    		cellId = ids[i];
				    		columnName = 'WAITTIME';
							val = jQuery('#s3list').jqGrid ('getCell', cellId, columnName);
							if (eval(val + lotStatusModel.redColorCon)) {
								color = '#FE4545';
							} else if (eval(val + lotStatusModel.yellowColorCon)) {
								color = 'yellow';
							}
							if (color !='')
							{
								jQuery('#s3list').jqGrid('setCell',cellId,columnName,"",{'background-color':color,'color': 'black', 'background-image':'none'});
							}
				      };

	                },
				    onRightClickRow: function (rowid) {
				        jQuery("#s3list").contextMenu('rightClickMenu', {
				            bindings: {
				                'CopyRow': function(t) {
				                	var rowids = jQuery('#s3list').getGridParam('selarrrow');
				        			if (rowids) {
				        				getRowData(rowids);
				        			}
				                }
				            },
				              menuStyle: {
				                //border: '',
				                width: '165px',
				                color: '#000000'
				              },
				              itemStyle: {
				                fontFamily : 'verdana',
				                fontSize : '80%',
				                //backgroundColor : '#94AEC4',
				                color: '#000000',
				                border: 'none',
				                padding: '1px',
				                height: '15px',
				                align: 'center'
				              },
				              itemHoverStyle: {
				                color: '#FFFFFF',
				                backgroundColor: '#567F9F',
				                color: 'white',
				                border: 'none'
				              }

				        });
				    }
				});
	
	
	
	jQuery("#s3list").jqGrid('navGrid', '#s3pager', {
		edit : false,
		add : false,
		del : false,
		search : false,
		refresh : false
	});
	/*
	jQuery("#s3list").jqGrid('navButtonAdd', "#s3pager", {
		caption : "Toggle",
		title : "Toggle Search",
		buttonicon : 'ui-icon-pin-s',
		onClickButton : function() {
			mygrid[0].toggleToolbar();
		}
	});
	*/
	jQuery("#s3list").jqGrid('navButtonAdd', "#s3pager", {
		caption : "Clear",
		title : "Clear Filter Values",
		buttonicon : 'ui-icon-refresh',
		onClickButton : function() {
			mygrid[0].clearToolbar();
		}
	});
	jQuery("#s3list").jqGrid('navButtonAdd','#s3pager',{
		caption:"Export to Excel",
		buttonicon : 'ui-icon-disk',
		onClickButton : function () {
			sendJsonData("exportExcel.do");
		}
	});
	jQuery("#s3list").jqGrid('navButtonAdd','#s3pager',{
		caption:"Export to PDF",
		buttonicon : 'ui-icon-document',
		onClickButton : function () {
			sendJsonData("exportPdf.do");
		/*
		jQuery("#s3list").jqGrid('excelExport', 
				{ url: 'exportPdf.do'});
		}
		*/
		}
	});
	
	jQuery("#s3list").jqGrid('navButtonAdd','#s3pager',{
		caption:"Copy",
		title : "Copy to Clipboard",
		buttonicon : 'ui-icon-copy',
		onClickButton : function () {
			//var rowids = jQuery("#s3list").jqGrid('getGridParam', 'selrow');
			var rowids = jQuery('#s3list').getGridParam('selarrrow');
			if (rowids) {
				getRowData(rowids);
			} else {
				alert("No selected row!!!");
			}
		}
	});
	
	jQuery("#s3list").jqGrid('filterToolbar',{searchOnEnter : false, defaultSearch : "cn"});
	
	jQuery("#s3list").jqGrid('setFrozenColumns');
	//fixPositionsOfFrozenDivs.call(jQuery("#s3list")); 
}

//handle jqGrid multiselect => thanks to solution from Byron Cobb on http://goo.gl/UvGku
var handleMultiSelect = function (rowid, e) {
//beforeSelectRow: function (rowid) {
    var $this = $(this), rows = this.rows,
        // get id of the previous selected row
        startId = $this.jqGrid('getGridParam', 'selrow'),
        startRow, endRow, iStart, iEnd, i, rowidIndex;

    if (!e.ctrlKey && !e.shiftKey) {
        $this.jqGrid('resetSelection');
    } else if (startId && e.shiftKey) {
        $this.jqGrid('resetSelection');

        // get DOM elements of the previous selected and the currect selected rows
        startRow = rows.namedItem(startId);
        endRow = rows.namedItem(rowid);
        if (startRow && endRow) {
            // get min and max from the indexes of the previous selected
            // and the currect selected rows 
            iStart = Math.min(startRow.rowIndex, endRow.rowIndex);
            rowidIndex = endRow.rowIndex;
            iEnd = Math.max(startRow.rowIndex, rowidIndex);
            for (i = iStart; i <= iEnd; i++) {
                // the row with rowid will be selected by jqGrid, so:
                if (i != rowidIndex) {
                    $this.jqGrid('setSelection', rows[i].id, false);
                }
            }
        }

        // clear text selection
        if(document.selection && document.selection.empty) {
            document.selection.empty();
        } else if(window.getSelection) {
            window.getSelection().removeAllRanges();
        }
    }
    return true;
};

function clearPreviousPostData() {
	var postData = $("#s3list").jqGrid('getGridParam','postData');
    try {
    	delete postData['department'];
    	delete postData['prodarea'];
    	delete postData['priority'];
    	delete postData['customername'];
    	delete postData['holdcode'];
    	delete postData['holdreason'];
    	// clear filter
    	$("#s3list")[0].clearToolbar();
    	// update current time
		jQuery("#s3list").setCaption("MEMS LOT STATUS " + displayNiceDateFormat(new Date()));
    	
    } catch (e) { }
}

function addGridSearchCriteria() {
	// default requirement to reload grid.
	var params = {datatype:'json', page:1, search : true};
	
	params.postData = getCurrentCondition();
	
	jQuery("#s3list").jqGrid("clearGridData", true).setGridParam(params);
}

function searchByFilter() {
	clearPreviousPostData();
	addGridSearchCriteria();
	jQuery("#s3list").trigger("reloadGrid");
}

function sendJsonData(url) {
	var result = '[';
	// build json string
	if (filteredData) {
		for (i = 0, n = filteredData.length; i < n; i++) {
			
			var data2 = JSON.stringify(filteredData[i]);
			result = result + data2;
			
			if (i < n - 1) {
				result = result + ',';
			}
		}
		result = result + ']';
	
		// build search condition
		var postData = $("#s3list").jqGrid('getGridParam', 'postData');
		var params = $.param(postData);
		$.download(url + '?' + params, 'jsonData=' + htmlEncode(result));
	} 
}